<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { CircleCheck, CircleClose, View } from '@element-plus/icons-vue'
import ReviewDetailDialog from '@/components/ReviewDetailDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reviewListService, reviewUpdateService, reviewUpdateBatchService } from '@/api/review.js'

// 类型定义
interface Review {
  id: number
  author: {
    nickname: string
  }
  content: string
  rating: number
  status: number // 0,1,2
  createTime: string
}

// 状态映射
const STATUS_MAP = {
  // 字符串状态 -> 数字状态
  all: null,
  pending: 0,
  approved: 1,
  rejected: 2,
  // 数字状态 -> 显示文本和样式
  0: { text: '待审核', type: 'warning' },
  1: { text: '已通过', type: 'success' },
  2: { text: '已拒绝', type: 'danger' }
} as const

// 组件属性
const props = defineProps({
  status: {
    type: String,
    default: 'all',
    validator: (value: string) => ['all', 'pending', 'approved', 'rejected'].includes(value)
  }
})

// 响应式数据
const loading = ref(false)
const data = ref<Review[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailDialogVisible = ref(false)
const currentReview = ref<Review | null>(null)

// 获取书评数据
const fetchReviews = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      // 将字符串状态转换为数字状态
      status: STATUS_MAP[props.status] ?? undefined
    }

    const result = await reviewListService(params)

    // 安全处理响应数据
    data.value = result?.data?.records || []
    total.value = result?.data?.total || 0

  } catch (error) {
    console.error('获取书评数据失败:', error)
    ElMessage.error('获取书评数据失败')
    data.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 操作函数
const handleApprove = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要通过这条书评吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const result = await reviewUpdateService(id, 1);
    ElMessage.success('书评已通过');
    fetchReviews()

  } catch (error) {
    // 用户点击取消或其他错误
    console.log('操作已取消', error);
  }
}

const handleReject = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要拒绝这条书评吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const result = await reviewUpdateService(id, 2);
    ElMessage.success('书评已拒绝');
    fetchReviews()

  } catch (error) {
    // 用户点击取消或其他错误
    console.log('操作已取消', error);
  }
}

const handleViewDetail = (row: Review) => {
  currentReview.value = row
  detailDialogVisible.value = true
}

const handleUpdate = () => {
  currentReview.value = null
  detailDialogVisible.value = false
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 监听refresh变化
watch(() => props.refresh, () => {
  fetchReviews(); // 你的获取数据方法
});

// 初始化加载数据
onMounted(fetchReviews)

// 添加判断是否可选的函数
const isSelectable = (row: Review, index: number) => {
  return props.status === 'pending'
}

// 添加批量选择的响应式数据
const selectedReviews = ref<number[]>([])

// 处理选择变化
const handleSelectionChange = (selection: Review[]) => {
  selectedReviews.value = selection.map(item => item.id)
}

// 批量通过
const handleBatchApprove = async () => {
  if (selectedReviews.value.length === 0) {
    ElMessage.warning('请至少选择一条书评')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要通过选中的 ${selectedReviews.value.length} 条书评吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 批量修改书评状态
    await reviewUpdateBatchService(selectedReviews.value, 1)

    ElMessage.success(`已通过 ${selectedReviews.value.length} 条书评`)
    fetchReviews()
    selectedReviews.value = []
  } catch (error) {
    console.log('操作已取消', error)
  }
}

// 批量拒绝
const handleBatchReject = async () => {
  if (selectedReviews.value.length === 0) {
    ElMessage.warning('请至少选择一条书评')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要拒绝选中的 ${selectedReviews.value.length} 条书评吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

   // 批量修改书评状态
   await reviewUpdateBatchService(selectedReviews.value, 2)

    ElMessage.success(`已拒绝 ${selectedReviews.value.length} 条书评`)
    fetchReviews()
    selectedReviews.value = []
  } catch (error) {
    console.log('操作已取消', error)
  }
}
</script>

<template>
  <div class="review-table-container">
    <!-- 书评表格 -->
    <el-table :data="data" border stripe v-loading="loading" style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :selectable="isSelectable" />
      <el-table-column prop="id" label="ID" width="80" show-overflow-tooltip />
      <el-table-column prop="author.nickname" label="用户" width="120" />
      <el-table-column prop="content" label="内容" show-overflow-tooltip />
      <el-table-column prop="rating" label="评分" width="150">
        <template #default="{ row }">
          <el-rate v-model="row.rating" disabled text-color="#ff9900" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="STATUS_MAP[row.status].type">
            {{ STATUS_MAP[row.status].text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="提交时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          <el-button v-if="row.status === 0" type="success" text :icon="CircleCheck" size="small"
            @click="handleApprove(row.id)">
            通过
          </el-button>
          <el-button v-if="row.status === 0" type="danger" text :icon="CircleClose" size="small"
            @click="handleReject(row.id)">
            拒绝
          </el-button>
          <el-button type="text" size="small" @click="handleViewDetail(row)">
            <el-icon>
              <View />
            </el-icon>
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="bottom">
      <div class="action" v-show="props.status === 'pending'">
        <el-button type="success" :icon="CircleCheck" @click="handleBatchApprove"
          :disabled="selectedReviews.length === 0">
          批量通过
        </el-button>
        <el-button type="danger" :icon="CircleClose" @click="handleBatchReject"
          :disabled="selectedReviews.length === 0">
          批量拒绝
        </el-button>
      </div>
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" background
          @size-change="fetchReviews" @current-change="fetchReviews" />
      </div>
    </div>

    <!-- 书评详情对话框 -->
    <ReviewDetailDialog v-model="detailDialogVisible" :review="currentReview" @update="handleUpdate" />
  </div>
</template>

<style scoped lang="scss">
.review-table-container {
  .bottom {
    margin-top: 20px;
    display: flex;

    .pagination {
      margin-left: auto;
    }
  }

  .el-table {
    :deep(.el-rate) {
      display: inline-flex;
    }
  }
}
</style>